package com.example.sj12;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class upload extends AppCompatActivity implements View.OnClickListener{
    private static final String TAG = "MainActivity";
    private static final int REQUEST_TAKE_PHOTO = 0;// 拍照
    private static final int REQUEST_CROP = 1;// 裁剪
    private static final int SCAN_OPEN_PHONE = 2;// 相册
    private static final int REQUEST_PERMISSION = 100;
    private static final int TIMW_OUT = 8000;
    private ImageView img;
    private Uri imgUri; // 拍照时返回的uri
    private Uri mCutUri;// 图片裁剪时返回的uri
    private boolean hasPermission = false;
    private File imgFile;// 拍照保存的图片文件
    private Button btn;
    private EditText name,housename,idcard,tel,price,lease,leasecustomer,introduce,type,area,toward;
    //int k;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload);
        Bundle bundle = this.getIntent().getExtras();
        final int picnumber = bundle.getInt("picnumber");
        System.out.println("picnumber值为："+picnumber);
        String n = getIntent().getStringExtra("username");
//        findViewById(R.id.btn_takephoto).setOnClickListener(this);
        //findViewById(R.id.btn_open_photo_album).setOnClickListener(this);
        img = findViewById(R.id.iv);
        findViewById(R.id.iv).setOnClickListener(this);
        checkPermissions();
        btn=findViewById(R.id.btn);
        name=findViewById(R.id.name);
        housename=findViewById(R.id.housename);
        idcard=findViewById(R.id.idcard);
        tel=findViewById(R.id.tel);
        price=findViewById(R.id.price);
        //lease=findViewById(R.id.lease);
        //leasecustomer=findViewById(R.id.leasecustomer);
        introduce=findViewById(R.id.introduce);
        type=findViewById(R.id.type);
        area=findViewById(R.id.area);
        toward=findViewById(R.id.toward);

        btn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                String n=name.getText().toString().trim();
                final String hn=housename.getText().toString().trim();
                final String id=idcard.getText().toString().trim();
                final String t=tel.getText().toString().trim();
                final String p=price.getText().toString().trim();
                //final String l=lease.getText().toString().trim();
                //final String lc=leasecustomer.getText().toString().trim();
                final String i=introduce.getText().toString().trim();
                final String tp=type.getText().toString().trim();
                final String a=area.getText().toString().trim();
                final String td=toward.getText().toString().trim();

                new Thread(new Runnable() {
                    private static final String TAG = "测试";

                    @Override
                    public void run() {
                        /*
                        UserDao u = new UserDao();
                        Data picnumber=u.GetPicnumber(getIntent().getStringExtra("username"));
                        if(picnumber.getPicnumber()==0){
                            k=1;
                        }
                        else
                            k=picnumber.getPicnumber()+1;
                        System.out.println("K值为："+k);*/

                        UserDao ud = new UserDao();
                        if(!ud.insert(getIntent().getStringExtra("username"),hn,id,t,p,i,tp,a,td,picnumber)){
                            Looper.prepare();
                            Toast.makeText(getApplicationContext(), "上传成功", Toast.LENGTH_SHORT).show();
                            Looper.loop();
                        }
                        /*
                        if (ud.check(n,btc.isChecked())) {
                            Looper.prepare();
                            Toast.makeText(RegisterActivity.this, "该用户名已被注册，注册失败", Toast.LENGTH_SHORT).show();
                            Looper.loop();
                        } else {

                            //UserDao u = new UserDao();
                            //boolean t=u.register(n, psw);
                            if (!ud.register(n, psw,btc.isChecked())) {
                                Looper.prepare();
                                Toast.makeText(RegisterActivity.this, "插入数据表成功", Toast.LENGTH_SHORT).show();
                                Looper.loop();
                            }
                        /*if (!result){
                            Looper.prepare();
                            Toast toast = Toast.makeText(RegisterActivity.this,"注册成功！",Toast.LENGTH_SHORT);
                            toast.show();
                            Looper.loop();
                        }
                            Log.i(TAG, "fun" + ud.register(n, psw,btc.isChecked()));
                            //以上为jdbc注册
                        }*/
                    }
                }).start();

            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv:
                checkPermissions();
                if (hasPermission) {
                    openGallery();
                }

                break;

            default:
                break;


        }

    }
    private void openGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK);//Intent打开一个Activity并从中选取一个想要的内容例如图片、用户号码等
        intent.setType("image/*");//指定类型setType
        startActivityForResult(intent, SCAN_OPEN_PHONE);
    }


    private void checkPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 检查是否有存储和拍照权限
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
                    && checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
            ) {
                hasPermission = true;
            } else {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, REQUEST_PERMISSION);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                hasPermission = true;
            } else {
                Toast.makeText(this, "权限授予失败！", Toast.LENGTH_SHORT).show();
                hasPermission = false;
            }
        }
    }

    // 图片裁剪
    private void cropPhoto(Uri uri, boolean fromCapture) {
        Intent intent = new Intent("com.android.camera.action.CROP"); //打开系统自带的裁剪图片的intent
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
/*
        // 注意一定要添加该项权限，否则会提示无法裁剪
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

        intent.putExtra("scale", true);

        // 设置裁剪区域的宽高比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        // 设置裁剪区域的宽度和高度
        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);
*/
        // 取消人脸识别
        intent.putExtra("noFaceDetection", true);
        // 图片输出格式
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());

        // 若为false则表示不返回数据
        intent.putExtra("return-data", false);

        // 指定裁剪完成以后的图片所保存的位置,pic info显示有延时
        if (fromCapture) {
            // 如果是使用拍照，那么原先的uri和最终目标的uri一致,注意这里的uri必须是Uri.fromFile生成的
            mCutUri = Uri.fromFile(imgFile);
        } else { // 从相册中选择，那么裁剪的图片保存在take_photo中
            String time = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA).format(new Date());
            String fileName = "photo_" + time;
            File mCutFile = new File(Environment.getExternalStorageDirectory() + "/take_photo/", fileName + ".jpeg");
            if (!mCutFile.getParentFile().exists()) {
                mCutFile.getParentFile().mkdirs();
            }
            mCutUri = Uri.fromFile(mCutFile);
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mCutUri);
        Toast.makeText(this, "剪裁图片", Toast.LENGTH_SHORT).show();
        // 以广播方式刷新系统相册，以便能够在相册中找到刚刚所拍摄和裁剪的照片
        Intent intentBc = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intentBc.setData(uri);
        this.sendBroadcast(intentBc);

        startActivityForResult(intent, REQUEST_CROP); //设置裁剪参数显示图片至ImageVie
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Bundle bundle = this.getIntent().getExtras();
        int picnumber = bundle.getInt("picnumber");
        System.out.println("picnumber值为："+picnumber);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                // 拍照并进行裁剪
                case REQUEST_TAKE_PHOTO:
                    Log.e(TAG, "onActivityResult: imgUri:REQUEST_TAKE_PHOTO:" + imgUri.toString());
                    cropPhoto(imgUri, true);
                    break;

                // 裁剪后设置图片
                case REQUEST_CROP:
                    img.setImageURI(mCutUri);
                    //Uri uri = data.getData();
                    //String img_src = uri.getPath();//选择图片的地址
                    //File compressedImage1File=new File(img_src);
                    String url="http://47.112.156.101/Uploadstx/Uploadstx";
                    new uploadLogFile(getApplicationContext(),url,mCutUri.getPath(),getIntent().getStringExtra("username"),picnumber);
                    //new uploadLogFile(compressedImage1File).execute("http://47.96.249.102/savePic/savePic");//后台的接口地址
                    Log.e(TAG, "onActivityResult: imgUri:REQUEST_CROP:" + mCutUri.toString());
                    break;
                // 打开图库获取图片并进行裁剪
                case SCAN_OPEN_PHONE:
                    Log.e(TAG, "onActivityResult: SCAN_OPEN_PHONE:" + data.getData().toString());
                    cropPhoto(data.getData(), false);
                    break;

                default:
                    break;
            }
        }
    }
}
